package com.gz.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/mange/*",initParams = {
        @WebInitParam(name = "topickey1",value = "苹果"),
        @WebInitParam(name = "topickey2",value = "香蕉")
})
public class Topicfilter implements Filter {

    private String topickey1;
    private String topickey2;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       topickey1 = filterConfig.getInitParameter("topickey1");
       topickey2 = filterConfig.getInitParameter("topickey2");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String topic = servletRequest.getParameter("topic");
        if(topic.contains(topickey1)||topic.contains(topickey2)){

            //注意这里servletRequest生命周期是一次请求
            // 转发是同一个request因为是在客户端，但重定向就不是同一个request
            //所以点击当你再次输入成功，点击返回重新输入时，用的是超链接(可以看做重定向，因为是新的请求))
            // error(Attribute)就消失了
            servletRequest.setAttribute("error","有违禁词");
            servletRequest.getRequestDispatcher("/topic.jsp").forward(servletRequest, servletResponse);
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
